import React, { useEffect, useState } from 'react';
import { useHistory } from "react-router-dom";
import {
    Modal, Toast, Picker, Button, List, TextareaItem,Switch,InputItem,DatePicker,Radio
} from 'antd-mobile';
import Input from "../../../components/input/Input";
import { dateFormat } from "../../../model/code";
import http from "../../../model/http";
import code from "../../../model/code"; 
import Header from "../../../components/header/Header";
import './add.less'

// import Vconsole from 'vconsole'
// const vConsole = new Vconsole()
const Item = List.Item
function Add() {
    const history = useHistory();
    // 回访类型下拉
    const [visitTypeData,setVisitTypeData] = useState([])
    // 回访方式下拉
    const [visitMethod, setVisitMethod] = useState([])
    // 沟通状态下拉
    const [visitStatus, setVisitStatus] = useState([])

     //计划回访人 名称
     const [planReturnVisitor,setPlanReturnVisitor] = useState()
      //计划回访人 id
      const [planReturnVisitorId,setPlanReturnVisitorId] = useState()



    // 回访类型值
    const [visitTypeVal,setVisitTypeVal] = useState([-1])
    // 回访方式
    const [visitMethodVal,setVisitMethodVal] = useState([-1])
    // 沟通状态
    const [visitStatusVal,setVisitStatusVal] = useState([-1])

    //是否有效沟通
    const [communicateState,setCommunicateState] = useState([-1])

    const [is_valid,setIs_valid] =useState([])

    // communicateState communicate
    const communicate=[
        {
            label:"是",
            value:1
        },
        {
            label:"否",
            value:0
        }
    ]



    // 回访目的
    const [purpose,setPurpose] = useState('')
    // 回访内容
    const [content, setContent] = useState('')
    const [addTypeVal, setAddTypeVal] = useState([])

    // 回访时间
    const [plan_date,setPlan_date] = useState()


    const [scout_state, setScout_state]=useState(1) 


   

    const getDataFunc = async (flag) => {
        const data = await http.post('/feedback/getFeedbackDictType',{
            flag:flag,
            customerCrmId: history.location.state.customerCrmId
        })
        if(flag == 1){
            let newData = data.data.map(item => {
                return {
                    label: item.name,
                    value: item.erp_id
                }
            })
            setVisitStatus(newData)
        }else if(flag == 2){
            // 回访类型
            let newData = data.data.map((item,index) => {
                return {
                    label: item.name,
                    value: item.erp_id ? item.erp_id : 'n'+index,
                    data: item
                }
            })
            setVisitTypeData(newData)
        }else if(flag == 3){
            let newData = data.data.map(item => {
                return {
                    label: item.name,
                    value: item.erp_id,
                    
                }
            })
            setVisitMethod(newData)
        }

      

        



    }
    /*渲染完成*/
    useEffect(async () => { 

        /**
         * originId  1   --> 来自工具栏
         *           2   --> 来自客户回访 标准回访
         */
 
        getDataFunc(1)
        getDataFunc(2)
        getDataFunc(3)



        setTimeout(()=>{
            if(history.location.state.originId == "2"){
                console.log("item",JSON.parse(history.location.state.item) )
               

                let data = visitTypeData.filter(item => { 
                    return item.value == JSON.parse(history.location.state.item).scout_type +"" 
                })
                if(data.length>0){
                     setVisitTypeVal([ JSON.parse(history.location.state.item).scout_type +"" ])
                     setAddTypeVal(data[0].data)
                }
                console.log("dataItem",data)
               
                let value= JSON.parse(history.location.state.item).scout_mode ? [ JSON.parse(history.location.state.item).scout_mode +"" ] :[-1]
        
                setVisitMethodVal(value)

                let value2= JSON.parse(history.location.state.item).receive_state ? [JSON.parse(history.location.state.item).receive_state+""] :[-1]
        
                setVisitStatusVal(value2)
        
        
                setContent(JSON.parse(history.location.state.item).scout_content||"" +"" )
        
                setPurpose( JSON.parse(history.location.state.item).scout_purpose||"" +"" )
                
        
            }
        },500)

       
         
    }, [])
    // radio
    const radioChange =async (num)=>{   
        setScout_state(num)
        if(num == 0){
            // http://wxwork.gzsg.cn/wxwork/feedback/searchFeedbackMan?userId=SG01016&hosId=1&managerId=1000920
            
            const data = await http.get('/feedback/searchFeedbackMan',{})
            console.log(data)
            setPlanReturnVisitor(data.username)
            setPlanReturnVisitorId(data.erp_id)





        }
    }
    // 计划回访人
    const getPlanReturnVisitor =(v) =>{



    }
    //搜索回访人
    const searchReturn =async (v)=>{
        //http://wxwork.gzsg.cn/wxwork/feedback/searchFeedbackMan?userId=SG01016&hosId=1&managerId=1000920&searchname=%E6%9D%8E%E5%A8%9F
        const data = await http.get('/feedback/searchFeedbackMan',{
            searchname:v
        })
        console.log("搜索结果",data)
        if(!data.erp_id){
            Toast.fail("查无此人")
        }else{
            setPlanReturnVisitor(data.username)
            setPlanReturnVisitorId(data.erp_id)
            Toast.success("查询成功")
        }
    }
    
    const getCommunicateState =(v)=>{
       
        let data = communicate.filter(item => { 
            return item.value == v[0]
        })
        console.log(data)
        setCommunicateState(v)
        setIs_valid(data[0].value)




    }

     
    // 回访类型
    const getVisitTypeVal = (v) => {
        setVisitTypeVal(v)
       
        let data = visitTypeData.filter(item => { 
            return item.value == v[0]
        })

        console.log(data)
        setAddTypeVal(data[0].data)
         
        
    }
    // 回访方式
    const getVisitMethodVal = (v) => {
        console.log(v)
        setVisitMethodVal(v)
    }
    // 沟通状态
    const getVisitStatusVal = (v) => {
        setVisitStatusVal(v)

    }
    const addSave = async () => { 
        // if(visitTypeVal[0] < 0){ Toast.fail('请选择回访类型'); return };
        // if(visitMethodVal[0] < 0){ Toast.fail('请选择回访方式'); return };
        // if(visitStatusVal[0] < 0){ Toast.fail('请选择沟通状态'); return };
        // if(purpose == ''){ Toast.fail('请输入回访目的'); return }; 
        // if(content == ''){ Toast.fail('请输入回访内容'); return }; 
        
        Modal.alert('提示', '确认提交回访记录', [
            { text: '取消' },
            {
              text: '提交', onPress: async () => {

              
                if(history.location.state.originId ==1){
                    if( scout_state == 0 ){

                        // scout_content不传，receive_state不传，scout_mode不传，
                        //scout_type必传，scout_type_name必传，scout_purpose必传，scout_state=0，plan_date手动选择日期，
    
                        if(!plan_date){
                            Toast.fail("请选择计划回访时间")
                            return
                        }
    
                        if(!addTypeVal.erp_id){
                            Toast.fail("请选择回访类型")
                            return
                        }
    
                        if(!purpose){
                            Toast.fail("请填写回访目的")
                            return
                        }
                         
    
                        let data ={
                                 scout_purpose: purpose,
                                 customerCrmId: history.location.state.customerCrmId,
                                 scout_type: addTypeVal.erp_id != undefined ? addTypeVal.erp_id : '', // 回访类型
                                 scout_type_name: addTypeVal.name, // 回访类型名称
                                 scout_state:0,
                                 plan_date:dateFormat(plan_date, 'yyyy-MM-dd'),
                                 scout_man_id:planReturnVisitorId
                        }
                         
                        // customerCrmId: history.location.state.customerCrmId,
                        // scout_type: addTypeVal.erp_id != undefined ? addTypeVal.erp_id : '', // 回访类型
                        // scout_type_name: addTypeVal.name, // 回访类型名称
                       
                        // receive_state: visitStatusVal[0],
                        // scout_mode: visitMethodVal[0],
    
    
                        //  scout_purpose: purpose,
                        // scout_content: content,
    
                        const addRes = await http.post('/feedback/addFeedback',data)
                        console.log(addRes)
                        if(addRes.code == 0){
                            Toast.success('保存成功')
                                setTimeout(() => {
                                history.go(-1)
                            }, 500); 
                        }else{
                            Toast.fail(addRes.msg)
                        }
    
    
    
                    }  else{
                        if(!addTypeVal.erp_id){
                            Toast.fail("请选择回访类型")
                            return
                        }
                        if(visitMethodVal < 0){ Toast.fail('请选择回访方式'); return };
                        if(visitStatusVal < 0){ Toast.fail('请选择沟通状态'); return };
                        if(purpose == ''){ Toast.fail('请输入回访目的'); return }; 
                        if(is_valid.length ==0 ){  Toast.fail('请选择是否有效沟通'); return  }
                        
                      
                       
                        
                        let data ={
                            
                            
                            customerCrmId: history.location.state.customerCrmId,
                            scout_type: addTypeVal.erp_id != undefined ? addTypeVal.erp_id : '', // 回访类型
                            scout_type_name: addTypeVal.name, // 回访类型名称
                            scout_state:1,
    
                            scout_mode:visitMethodVal[0],
                            receive_state:visitStatusVal[0],
                            is_valid:is_valid,
                            scout_content: content,
                             scout_purpose: purpose,
                          
                   }
    
                   console.log("data1",data)
    
                        const addRes = await http.post('/feedback/addFeedback',data)
                        console.log(addRes)
                        if(addRes.code == 0){
                            Toast.success('保存成功')
                                setTimeout(() => {
                                history.go(-1)
                            }, 500); 
                        }else{
                            Toast.fail(addRes.msg)
                        }
    
    
    
    
    
    
                    }
    
                }
                
                if(history.location.state.originId ==2){
                             if(!addTypeVal.erp_id){
                        Toast.fail("请选择回访类型")
                        return
                    }
                    if(visitMethodVal < 0){ Toast.fail('请选择回访方式'); return };
                    if(visitStatusVal < 0){ Toast.fail('请选择沟通状态'); return };
                    if(purpose == ''){ Toast.fail('请输入回访目的'); return }; 
                    if(is_valid.length ==0 ){  Toast.fail('请选择是否有效沟通'); return  }
                    
                  
                   
                            
                            let data ={   
                                customerCrmId: history.location.state.customerCrmId,
                                scout_type: addTypeVal.erp_id != undefined ? addTypeVal.erp_id : '', // 回访类型
                                scout_type_name: addTypeVal.name, // 回访类型名称
                                // scout_state:1,
                                tb_feedback_id:history.location.state.tb_feedback_id,
                                scout_mode:visitMethodVal[0],
                                receive_state:visitStatusVal[0],
                                is_valid:is_valid,
                                scout_content: content,
                                scout_purpose: purpose,
                            
                            }

                            const addRes = await http.post('/feedback/updateFeedback',data)
                            console.log(addRes)
                            if(addRes.code == 0){
                                Toast.success('保存成功')
                                    setTimeout(() => {
                                    history.go(-1)
                                }, 500); 
                            }else{
                                Toast.fail(addRes.msg)
                            }

                    console.log("data1",data)
                }
                
            //     else{
                    
            //         if(!addTypeVal.erp_id){
            //             Toast.fail("请选择回访类型")
            //             return
            //         }
            //         if(visitMethodVal < 0){ Toast.fail('请选择回访方式'); return };
            //         if(visitStatusVal < 0){ Toast.fail('请选择沟通状态'); return };
            //         if(purpose == ''){ Toast.fail('请输入回访目的'); return }; 
            //         if(is_valid.length ==0 ){  Toast.fail('请选择是否有效沟通'); return  }
                    
                  
                   
                    
            //         let data ={   
            //             customerCrmId: history.location.state.customerCrmId,
            //             scout_type: addTypeVal.erp_id != undefined ? addTypeVal.erp_id : '', // 回访类型
            //             scout_type_name: addTypeVal.name, // 回访类型名称
            //             // scout_state:1,
            //             tb_feedback_id:history.location.state.tb_feedback_id,
            //             scout_mode:visitMethodVal[0],
            //             receive_state:visitStatusVal[0],
            //             is_valid:is_valid,
            //             scout_content: content,
            //             scout_purpose: purpose,
                      
            //         }

            //         const addRes = await http.post('/feedback/updateFeedback',data)
            //         console.log(addRes)
            //         if(addRes.code == 0){
            //             Toast.success('保存成功')
            //                 setTimeout(() => {
            //                 history.go(-1)
            //             }, 500); 
            //         }else{
            //             Toast.fail(addRes.msg)
            //         }

            //    console.log("data1",data)

            //     }






              }
            }
        ])

        
    }
     
    return (
        <div>
            <div className="v-return-visit-add">
                <div className='body-background-div'></div>
               {
                  ( history.location.state.originId ==1 ) ?(
                    <div className='myRadio'>
                            <div className='radioItem'  onClick={ ()=>{ radioChange("0")}}> 
                                    {
                                        scout_state == 0?(
                                            <div className='selectR' ></div>
                                        ):(
                                            <div className='default' ></div>  
                                        )
                                    }    
                                    <div>计划回访</div>
                            </div>           
                            <div className='radioItem'  style={{marginLeft:'20px'}}  onClick={ ()=>{ radioChange("1")}}> 
                                    {
                                        scout_state == 1?(
                                            <div className='selectR' ></div>
                                        ):(
                                            <div className='default' ></div>  
                                        )
                                    }    
                                    <div>实际回访</div>
                            </div>
                            </div>
                   ) :null


               }


               {
                  ( history.location.state.originId ==2 ) ?(
                    <div className='myRadio'>
                            {/* <div className='radioItem'  onClick={ ()=>{ radioChange("0")}}> 
                                    {
                                        scout_state == 0?(
                                            <div className='selectR' ></div>
                                        ):(
                                            <div className='default' ></div>  
                                        )
                                    }    
                                    <div>计划回访</div>
                            </div>            */}
                            <div className='radioItem'  style={{marginLeft:'20px'}}  onClick={ ()=>{ radioChange("1")}}> 
                                    {
                                        scout_state == 1?(
                                            <div className='selectR' ></div>
                                        ):(
                                            <div className='default' ></div>  
                                        )
                                    }    
                                    <div>实际回访</div>
                            </div>
                            </div>
                   ) :null


               }
       
       

             
               
               <List className='g-p5-10 g-bg-f g-bdrs12 g-mb10 customer'>
                     <Item wrap extra={history.location.state.customerName}>回访客户</Item>

                     {/* <Item wrap extra={'嘿嘿'}>回访客户</Item> */}

               </List>
                
                { scout_state == '0' ? (

                    <List className='g-p5-10 g-bg-f g-bdrs12 g-mb10 plan_date' >
                                
                        <List.Item extra={
                          <DatePicker mode="date" value={plan_date}  onChange={d => { setPlan_date(d)}}>
                             <List.Item arrow="horizontal"></List.Item>
                           </DatePicker> 
                        }>
                          计划回访时间
                        </List.Item>
                    </List>
                        ) :(
                           null
                        )   }

                <List className='g-p5-10 g-bg-f g-bdrs12 g-mb10'>
                    <Picker data={visitTypeData} cols={1}
                    value={visitTypeVal} onOk={v => getVisitTypeVal(v)}
                    >
                        <Item arrow="horizontal">回访类型</Item>
                    </Picker>
                    { scout_state == '0' ? (
                    <div>
                       <Input onSubmit={(v)=> searchReturn(v)}  placeholder='可根据姓名搜索回访人' />

                        <div className='jhhfr'>
                            <span>计划回访人:</span>
                            <span style={{marginLeft:'12px'}}>{planReturnVisitor}</span>

                        </div>
                    </div>
                   
                   


                    ) :(
                        null
                    )   } 
                    
                </List>

                { 
                   scout_state == 1 ? (
                       <div>       
                        <List className='g-p5-10 g-bg-f g-bdrs12' style={{marginTop:"5px"}}>
                        <Picker data={visitMethod} cols={1}
                            value={visitMethodVal} onOk={v => getVisitMethodVal(v)}>
                                <Item arrow="horizontal">回访方式</Item>
                            </Picker>
                            <Picker data={visitStatus} cols={1}
                            value={visitStatusVal} onOk={v => getVisitStatusVal(v)}>
                                <Item arrow="horizontal">沟通状态</Item>
                            </Picker> 

                            <Picker data={communicate} cols={1}
                            value={communicateState} onOk={v => getCommunicateState(v)}>
                                <Item arrow="horizontal">是否有效沟通</Item>
                            </Picker>
                        </List>
                        <List className='g-p5-10 g-bg-f g-bdrs12' style={{marginTop:'5px'}}>
                            <TextareaItem value={content} rows={3} count={1000} onChange={v => {setContent(v)}} className="input-css" placeholder='请输入回访内容...' />
                        </List> 
                       </div>
                   ) :(
                       <div></div>
                   )                
                }

               <List className='g-p5-10 g-bg-f g-bdrs12' style={{marginTop:'5px'}}>
                    <TextareaItem value={purpose} rows={3} count={50} onChange={v => {setPurpose(v)}} className="input-css" placeholder='请输入回访目的...' />
                </List> 

                <Button style={{marginTop:'20px'}} className="add-btn" type="primary" onClick={addSave}>提交</Button>
            </div>
            <Header/>
        </div>
    )
}   
export default Add;